<template>
    <div class="building-structure-wrap">
        <el-form v-if="$store.state.userinfo.isMuilUnitUser === 1" :inline="true" class="demo-form-inline" style="text-align: left;" @submit.native.prevent>
            <el-form-item>
                <el-select filterable @change="getBuildTree(false)" v-model="selectedOrgId" placeholder="请选择业主单位">
                    <el-option
                        v-for="item in orgOptions"
                        :key="item.organizationId"
                        :label="item.shortName"
                        :value="item.organizationId">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <el-container>
            <el-aside width="500px" style="padding: 20px;">
                <p>建筑树结构</p>
                <el-tree
                    v-if="loadTree"
                    :data="treeData"
                    node-key="id"
                    highlight-current
                    :expand-on-click-node="false"
                    :default-expanded-keys="defaultExpandedKeys"
                    @node-click="handleTreeNodeClick"
                    :props="defaultProps"
                    :current-node-key="selectBuildNodeId">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span>
                            <el-button v-if="data.parentId != 0" @click="handleUp(node, data)" type="text" size="small">上移</el-button>
                            <el-button v-if="data.parentId != 0" @click="handleDown(node, data)" type="text" size="small">下移</el-button>
                            <el-button @click="handleEdit(node, data)" type="text" size="small">编辑</el-button>
                            <el-button v-if="data.parentId != 0" @click="handleDelete(node, data)" type="text" size="small">删除</el-button>
                        </span>
                    </span>
                </el-tree>
            </el-aside>
            <el-main>
                <div class="table-header-wrap">
                    <p>子节点清单</p>
                    <div class="more-btns">
                        <el-button v-show="hasAddBtn" type="primary" @click="addNewNode">新增子节点</el-button>
                        <el-dropdown @command="handleCommand">
                            <span class="el-dropdown-link">
                                更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="allExport">导出单位建筑物</el-dropdown-item>
                                <!-- <el-dropdown-item command="conditionExport">按当前条件导出二维码</el-dropdown-item> -->
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </div>
                <el-table
                    v-loading="loading"
                    :data="tableData"
                    ref="mainTable"
                    style="width: 100%">
                    <el-table-column
                        label="序号"
                        type="index"
                        width="50">
                    </el-table-column>
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="节点属性" prop="type">
                        <template slot-scope="scope">
                            <p v-if="scope.row.type == 1">单位</p>
                            <p v-else-if="scope.row.type == 2">片区</p>
                            <p v-else-if="scope.row.type == 3">楼栋</p>
                            <p v-else-if="scope.row.type == 4">楼层</p>
                            <p v-else-if="scope.row.type == 5">分区</p>
                            <p v-else>-</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="节点层级">
                        <template>
                            <p>{{level}}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序号" prop="sort"></el-table-column>
                    <el-table-column label="二维码" prop="visualCode">
                        <template slot-scope="scope">
                            <el-popover
                                placement="top"
                                width="320"
                                trigger="hover">
                                <div class="qr-hover-wrap">
                                    <vue-qr
                                    :text="scope.row.visualCode || ''"
                                    :size="200"
                                    :margin="0"
                                    :dotScale="1"
                                    ></vue-qr>
                                    <p class="qr-code-text">{{ scope.row.visualCode }}</p>
                                </div>
                                <vue-qr v-if="scope.row.visualCode" slot="reference" :text="scope.row.visualCode||''" :size="50" :margin="0" :dotScale="0.75"></vue-qr>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="经度" prop="lat"></el-table-column>
                    <el-table-column label="纬度" prop="lon"></el-table-column>
                    <!-- <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button @click="handleUp(scope.row)" type="text" size="small">上移</el-button>
                            <span class="dividing-line">|</span>
                            <el-button @click="handleDown(scope.row)" type="text" size="small">下移</el-button>
                            <span class="dividing-line">|</span>
                            <el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
                            <span class="dividing-line">|</span>
                            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 50, 100]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </el-main>
        </el-container>
        <!-- 新增/编辑建筑节点信息弹框 -->
        <el-dialog
            :close-on-click-modal="false"
            :title="dialogTitle"
            width="650px"
            top='10vh'
            v-if="dialogBuildNodeInfo"
            :visible.sync="dialogBuildNodeInfo"
            @close="closeBuildNodeInfo"
            v-dialogDrag>
            <build-node-info-form :organizationId="selectedOrgId" :closeDialogFun="closeBuildNodeInfo" :hasChildNodes="selectBuildNodeHasChildNodes" :oldInfo="selectBuildNodeInfo" :parentId="selectBuildNodeParentId" :parentType="selectBuildNodeParentType" :parentName="selectBuildNodeParentName" :isAddChild="isAddChild"></build-node-info-form>
        </el-dialog>
        <!-- 二维码详情弹框 -->
        <el-dialog
            :close-on-click-modal="false"
            title="二维码"
            width="650px"
            top='20vh'
            :visible.sync="dialogVisualCodeInfo"
            @close="dialogVisualCodeInfo = false"
            v-dialogDrag>
            <div class="visual-code-detail-wrap">
                <div id="visualCodeDetail" class="visual-code-detail"></div>
                <p>{{visualCodeInfo.code}}</p>
                <p>{{visualCodeInfo.text}}</p>
                <el-button type="primary" @click="exprotVisualCode">导出</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getOrgList} from '@/api/org'
import { getFbsTree, getFbsListExt, delFbs } from '@/api/sysConfig'
import { getFbs } from '@/api/fbs'
import buildNodeInfoForm from './Dialog/BuildNodeInfoForm'
import { statSync } from 'fs';
import { setTimeout } from 'timers';

export default {
    name: 'BuildingStructure',
    components: {
        buildNodeInfoForm
    },
    data() {
        return {
            loadTree: false,
            loading: false,
            hasAddBtn: true,
            defaultExpandedKeys: [], // 默认展开的节点
            isAddChild: false, // 是否新增子节点
            dialogTitle: '新增子节点',
            dialogBuildNodeInfo: false,
            dialogVisualCodeInfo: false,
            orgOptions: [],
            selectedOrgId: '', // 当前选择的业主单位
            selectBuildNodeId: '', // 当前选择的节点Id
            selectBuildNodeHasChildNodes: false, // 当前选择的节点是否有子集
            selectBuildNodeInfo: {}, // 当前选择的建筑节点信息
            selectBuildNodeParentId: '', // 当前选择的节点的父节点Id
            selectBuildNodeParentType: '', // 当前选择的节点的父节点Type
            selectBuildNodeParentName: '', // 当前选择的节点的父节点Text
            treeData: [],
            defaultProps: {
                children: 'nodes',
                label: 'text',
                value: 'id'
            },
            tableData: [],
            level: 1,
            total: 0,
            currentPage: 1,
            pageSize: 10,
            visualCodeInfo: {
                code: '',
                text: ''
            }
        }
    },
    created() {
        let that = this
        if(that.$store.state.userinfo.isMuilUnitUser === 1) {
            // 绑定下拉框
            getOrgList({queryType: 0}).then(res => {
                that.orgOptions = res.data
                // 默认展示第一个单位
                that.selectedOrgId = res.data[0].organizationId
                that.getBuildTree()
            })
        } else {
            that.selectedOrgId = that.$store.state.userinfo.org.id
            that.getBuildTree()
        }
    },
    methods: {
        getBuildTree(isAddChild) {
            let that = this
            that.loadTree = false
            that.hasAddBtn = true
            // 树型建筑结构
            getFbsTree({organizationId: that.selectedOrgId}).then(res => {
                // 设置默认展开的节点
                that.defaultExpandedKeys = [res.data[0].id]
                that.treeData = res.data
                if(!isAddChild) {
                    // 父节点
                    that.selectBuildNodeParentId = res.data[0].id
                    that.selectBuildNodeParentType = res.data[0].type
                    that.selectBuildNodeParentName = res.data[0].text
                    // 默认加载第一个节点
                    that.selectBuildNodeId = res.data[0].id
                    // 默认加载第一个节点的节点信息
                    that.selectBuildNodeInfo = res.data[0]
                }
                that.loadTree = true
                that.getTableData(1)
            })
        },
        // 树型节点被点击
        handleTreeNodeClick(obj, node, item) {
            let that = this
            // 最低一级没有新增子节点按钮
            if(obj.type == 5) {
                that.hasAddBtn = false
            } else {
                that.hasAddBtn = true
            }
            // 是否含有子节点
            that.selectBuildNodeHasChildNodes = (obj.nodes && obj.nodes.length > 0) ? true : false
            // 当前选择的节点信息
            that.selectBuildNodeInfo = obj
            // 父节点
            that.selectBuildNodeParentId = obj.parentId || ''
            that.selectBuildNodeParentType = node.parent.data.type
            that.selectBuildNodeParentName = node.parent.label
            // 节点层级赋值
            that.level = node.level
            that.selectBuildNodeId = obj.id
            // 渲染列表
            that.getTableData(1)
        },
        getTableData(_pageIndex, _pageSize) {
            if(_pageIndex){
                this.currentPage = _pageIndex
            }
            if(_pageSize){
                this.pageSize = _pageSize
            }
            let that = this
            let parames = {
                organizationId: that.selectedOrgId,
                parentId: that.selectBuildNodeId,
                queryType: 1,
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize
            }
            that.loading = true
            getFbsListExt(parames).then(res => {
                let data = res.data
                for(var i=0, len=data.length; i < len; i++) {
                    delete data[i].hasChildren
                }
                that.tableData = data
                that.total = res.total
                that.loading = false
            })
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        // 新增子节点
        addNewNode() {
            let that = this
            getFbs({id: that.selectBuildNodeInfo.id}).then(res => {
                if(res.status === 200) {
                    that.selectBuildNodeInfo = res.data
                    that.isAddChild = true
                    that.dialogTitle = '新增子节点'
                    that.dialogBuildNodeInfo = true
                }
            })
        },
        // 更多操作
        handleCommand(command) {
            let that = this

            switch (command) {
                case 'allExport':
                    that.allExport()
                    return false
                case 'conditionExport':
                    that.conditionExport()
                    return false
                default:
                    return false
            }
        },
        // 导出全部二维码
        allExport() {
            // this.$message.warning('抱歉，该功能暂未实现')
            let that = this
            let downloadUrl = this.GLOBAL.baseURL + 'fbs/exportFbs?orgId=' + that.selectedOrgId
            window.open(downloadUrl)
        },
        // 按条件导出二维码
        conditionExport() {
            this.$message.warning('抱歉，该功能暂未实现')
        },
        // 关闭建筑节点信息弹框
        closeBuildNodeInfo(flag) {
            this.dialogBuildNodeInfo = false
            if(typeof(flag) !== 'object' && flag) {
                // 刷新页面
                this.getBuildTree(true)
            }
        },
        // 点击二维码
        openVisualCodeDetail(row) {
            let that = this
            if(row) {
                // 弹出二维码详情弹框
                that.dialogVisualCodeInfo = true
                setTimeout(() => {
                    let dom = document.getElementById('visualCodeDetail')
                    that.visualCodeInfo = {code: row.visualCode, text: row.name}//res.data
                    // 渲染二维码
                    
                }, 0)
                // 查询二维码详细信息
                // getVisualCodeInfo().then(res => {
                        // that.visualCodeInfo = res.data
                        // 渲染二维码
                       
                //     } else {
                //         that.$message({
                //             message: res.info,
                //             type: 'warning'
                //         })
                //     }
                // })
            }
        },
        // 导出单个二维码
        exprotVisualCode(code) {
            this.$message.warning('抱歉，该功能暂未实现')
        },
        // 上移
        handleUp(node, data) {
            this.$message.warning('抱歉，该功能暂未实现')
        },
        // 下移
        handleDown(node, data) {
            this.$message.warning('抱歉，该功能暂未实现')
        },
        // 编辑
        handleEdit(node, data) {
            let that = this
            that.isAddChild = false
            that.dialogTitle = '编辑节点'
            if(data) {
                that.selectBuildNodeHasChildNodes = (data.nodes && data.nodes.length > 0) ? true : false
                getFbs({id: data.id}).then(res => {
                    if(res.status === 200) {
                        that.selectBuildNodeInfo = res.data
                        that.dialogBuildNodeInfo = true
                    }
                })
            }
        },
        // 删除
        handleDelete(node, data) {
            // 阻止事件冒泡
            event.stopPropagation()
            let that = this
            if(data) {
                this.$confirm('删除当前节点后，其子节点同时会被删除，并且不可恢复。是否确定删除当前节点？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    delFbs({
                        organizationId: that.selectedOrgId,
                        id: data.id
                    }).then(res => {
                        if(res.status === 200) {
                            that.$message({
                                message: '删除成功！',
                                type: 'success'
                            })
                            // 刷新页面
                            that.getBuildTree()
                        } else {
                            that.$message({
                                message: res.info,
                                type: 'warning'
                            })
                        }
                    })
                    // 阻止事件冒泡
                    event.stopPropagation()
                }).catch(() => {

                })     
            }
        }
    }
}
</script>
<style lang="scss">
.building-structure-wrap {
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
    .table-header-wrap {
        .more-btns {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
            padding-right: 20px;
            .el-dropdown {
                margin-left: 20px;
                padding: 0 10px;
                height: 40px;
                line-height: 40px;
                border: 1px solid #409EFF;
                border-radius: 3px;
            }
        }
    }
    .visual-code-detail-wrap {
        margin-bottom: 20px;
        text-align: center;
        .visual-code-detail {
            margin: 0 auto;
            width: 150px;
            height: 150px;
        }
        p,
        .el-button {
            margin-top: 15px;
        }
    }
} 

.qr-hover-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  .qr-code-text {
    margin-top: 10px;
  }
}
</style>
